package config

import (
	"io/ioutil"
	"log"
	"os"
	"path"

	"gitee.com/zawei/yggdrasil/pkg"
	"gitee.com/zawei/yggdrasil/pkg/config/source"
	"gitee.com/zawei/yggdrasil/pkg/config/source/cli"
	"gitee.com/zawei/yggdrasil/pkg/config/source/env"
	"gitee.com/zawei/yggdrasil/pkg/config/source/file"
)

func init() {
	sources := []source.Source{
		cli.NewSource(),
		env.NewSource(env.WithPrefix(pkg.AppName()), env.WithStrippedPrefix(pkg.AppName())),
	}
	if err := Load(sources...); err != nil {
		log.Fatal(err.Error())
	}
	configDir := Get("config.path").String("./conf")

	if _, err := os.Stat(configDir); err == nil {
		fileInfoList, err := ioutil.ReadDir(configDir)
		if err != nil {
			log.Fatalf("fault to read config directory[%s], error: %s", configDir, err.Error())
		} else {
			fileSource := make([]source.Source, 0)
			for i := range fileInfoList {
				if !fileInfoList[i].IsDir() {
					filePath := path.Join(configDir, fileInfoList[i].Name())
					fileSource = append(fileSource, file.NewSource(file.WithPath(filePath), file.WithWatch(true)))
				}
			}
			if err := Load(fileSource...); err != nil {
				log.Fatalf(err.Error())
			}
		}
	} else if !os.IsNotExist(err) || configDir != "./conf" {
		log.Fatalf(err.Error())
	}
}
